package com.pn.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Servlet;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * 配置durid连接池，设置后台监控
 */
@Configuration
public class DruidConfig {

    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource duridDataSource(){
        return new DruidDataSource();
    }

    //后台监控
    // SpringBoot 没有web.xml 用registrationbean 去替代
    @Bean
    public ServletRegistrationBean statViewServlet(){
        ServletRegistrationBean<StatViewServlet> srBean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");

        //后台登录的账号密码设置
        HashMap<String,String> initParameters = new HashMap<>();

        //增加配置
        initParameters.put("loginUsername","admin");
        initParameters.put("loginPassword","123456");

        //允许谁可以访问
        initParameters.put("allow","");

        //禁止谁可以访问 initParameters.put("cgy","localhost");

        //设置初始化参数
        srBean.setInitParameters(initParameters);
        return srBean;
    }

    //filter
    public FilterRegistrationBean webStatFilter(){
        FilterRegistrationBean frBean = new FilterRegistrationBean();

        //WebStatFilter用于配置Web和Druid数据源之间的管理关联监控统计
        frBean.setFilter(new WebStatFilter());

        Map<String, String> initParameters = new HashMap<>();

        //这些不进行统计
        initParameters.put("exclusions","*.js,*.css,/druid/*");

        frBean.setInitParameters(initParameters);

        return frBean;
    }

}
